package com.yiwei.zhh.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.Html;
import android.text.Spanned;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.yiwei.zhh.R;
import com.yiwei.zhh.constant.Const;
import com.yiwei.zhh.event.OnChsiRegisterEventMsg;
import com.yiwei.zhh.event.OnVerifyEventMsg;
import com.yiwei.zhh.http.InfoCallBack;
import com.yiwei.zhh.impl.ChsiCallBack;
import com.yiwei.zhh.impl.ChsiInfoImpl;
import com.yiwei.zhh.model.ChsiModel;
import com.yiwei.zhh.model.ResponseModel;
import com.yiwei.zhh.util.ImageUtil;
import com.yiwei.zhh.util.ToastUtil;
import com.yiwei.zhh.util.Util;
import com.yiwei.zhh.view.CircularProgress;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by xsooy-pc on 2017/5/18.
 * 学信网
 */

public class ChsiActivity extends BaseActivity implements View.OnClickListener {
    private LinearLayout codeView;
    private EditText username, password, code;
    private ImageView codeIv;
    private CircularProgress loading;
    private ImageView mIv;
    private Bitmap bitmap;
    private TextView okBtn, forget, agree, register;
    private CheckBox cb;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setBaseContentView(R.layout.new_fragment_chsi);
        baseInitView(this, "BankEditActivity", Const.ViewType.ACTIVITY);
        initView();
        EventBus.getDefault().register(this);
    }

    private void initView() {
        setBackIntent();
        mIv = (ImageView) findViewById(R.id.chsi_iv);
        bitmap = ImageUtil.readBitMap(this, R.mipmap.chsi);
        mIv.setImageBitmap(bitmap);
        cb = (CheckBox) findViewById(R.id.cb);
        loading = (CircularProgress) findViewById(R.id.progressBar);
        okBtn = (TextView) findViewById(R.id.ok);
        username = (EditText) findViewById(R.id.username);
        password = (EditText) findViewById(R.id.password);
        code = (EditText) findViewById(R.id.code);
        codeView = (LinearLayout) findViewById(R.id.code_view);
        codeIv = (ImageView) findViewById(R.id.code_iv);
        forget = ((TextView) findViewById(R.id.forget));
        agree = ((TextView) findViewById(R.id.agree));
        ((TextView) findViewById(R.id.register)).setOnClickListener(this);
        forget.setOnClickListener(this);
        agree.setOnClickListener(this);
        codeIv.setOnClickListener(this);
        okBtn.setOnClickListener(this);

        StringBuilder sb = new StringBuilder();
        sb.append(getResources().getString(R.string.read_and_agree));
        sb.append("<font color='#e3483d'>");
        sb.append(getResources().getString(R.string.service_clause));
        sb.append("</font>");
        Spanned spanned = Html.fromHtml(sb.toString());
        agree.setText(spanned);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ok:
                if (!cb.isChecked())
                    ToastUtil.makeText(this, getResources().getString(R.string.please_agree_server), Toast.LENGTH_SHORT).show();
                else {
                    // sendBroadcast();
                    if (checkInput()) {
                        Util.getEventCount(this, "a_xjrz_qd");
//                        if (codeView.getVisibility() == View.VISIBLE)
                        getChsi();
//                        else getChsiCode();
                    }
                }
                break;
            case R.id.code_iv:
                Util.getEventCount(this, "a_xjrz_txyzm");
                if (checkInput())
                    getChsiCode();
                break;
            case R.id.agree:
                Util.getEventCount(this, "a_xjrz_fwtk");
                Intent intent = new Intent(this, AboutActivity.class);
                intent.putExtra("id", Const.ContractType.CHSI);
                intent.putExtra("type", 1);
                intent.putExtra("title", getResources().getString(R.string.service_contract_text2));
                startActivity(intent);
                this.overridePendingTransition(R.anim.right_enter, R.anim.left_out);
                break;
            case R.id.register:
                Util.getEventCount(this, "a_xjrz_zcxxw");
                Util.startActivity(this, ChsiRegisterActivity.class);
//                ToastUtil.makeText(this, "敬请期待...", Toast.LENGTH_SHORT).show();
                break;
            case R.id.forget:
                Util.getEventCount(this, "a_xjrz_wjmm");
                Util.startActivity(this, ChsiForgetPwdActivity.class);
//                ToastUtil.makeText(this, "敬请期待...", Toast.LENGTH_SHORT).show();
                break;
        }
    }


    /**
     * 是否显示加载框
     *
     * @param b
     */
    private void showLoading(boolean b) {
        if (b) {
            okBtn.setEnabled(false);
            if (loading != null) loading.setVisibility(View.VISIBLE);
        } else {
            okBtn.setEnabled(true);
            if (loading != null) loading.setVisibility(View.GONE);
        }
    }

    /**
     * 检查输入
     *
     * @return
     */
    private boolean checkInput() {
        if (TextUtils.isEmpty(username.getText().toString().trim())) {
            ToastUtil.makeText(this, getResources().getString(R.string.account_is_empty), Toast.LENGTH_SHORT).show();
            return false;
        }
        if (TextUtils.isEmpty(password.getText().toString().trim())) {
            ToastUtil.makeText(this, getResources().getString(R.string.password_is_empty), Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    /**
     * 事件监听
     *
     * @param msg
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void ChsiRegisterEventBus(OnChsiRegisterEventMsg msg) {
        Map<String, String> map = msg.getMsg();
        username.setText(map.get("mobile"));
    }

    /**
     * 获取学信网验证码
     */
    private void getChsiCode() {
        showLoading(true);
        new ChsiInfoImpl().getChsiCodeInfo(this, username.getText().toString().trim(), password.getText().toString().trim(), new InfoCallBack() {
            @Override
            public void onSuccess(Object o) {

                try {
                    String imgStr = "";
                    ChsiModel model = (ChsiModel) o;
                    if (model.getMsg().contains(",")) {
                        imgStr = model.getMsg().substring(model.getMsg().indexOf(',') + 1);
//                        RBLog.i("img:  ", imgStr);
                        codeIv.setImageBitmap(ImageUtil.stringtoBitmap(imgStr));

                        codeView.setVisibility(View.VISIBLE);
                    } else codeIv.setImageDrawable(null);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    showLoading(false);
                }

            }

            @Override
            public void onFailure(String cause) {
                ToastUtil.makeText(ChsiActivity.this, cause, Toast.LENGTH_SHORT).show();
                showLoading(false);
            }
        });
    }

    /**
     * 获取学信网信息
     */
    private void getChsi() {
        try {
            String codeS = "";
            if (!TextUtils.isEmpty(code.getText().toString()))
                codeS = URLEncoder.encode(code.getText().toString(), "utf-8");
            showLoading(true);
            new ChsiInfoImpl().getChsiInfo(this, username.getText().toString().trim(), password.getText().toString().trim(), codeS, new ChsiCallBack() {
                @Override
                public void getChsiLoginSuccess(ResponseModel item) {

                    showLoading(false);
                    ToastUtil.makeText(ChsiActivity.this, "认证成功").show();
                    finish();
                }

                @Override
                public void getChsiLoginFail(String item) {

                    showLoading(false);
                    ToastUtil.makeText(ChsiActivity.this, item).show();
                }

                @Override
                public void getChsiNeedCode(String code) {

                    showLoading(false);
                    if (codeView.getVisibility() == View.VISIBLE) {
                        ToastUtil.makeText(ChsiActivity.this, "图片验证码错误");
                    }
                    codeView.setVisibility(View.VISIBLE);
                    String imgStr = "";
                    if (code.contains(",")) {
                        imgStr = code.substring(code.indexOf(',') + 1);
                        codeIv.setImageBitmap(ImageUtil.stringtoBitmap(imgStr));
                    } else codeIv.setImageDrawable(null);
                }
            });
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (bitmap != null && !bitmap.isRecycled()) {
            bitmap.recycle();
            bitmap = null;
            System.gc();
        }
        ImageUtil.releaseImageViewResouce(mIv);
        ImageUtil.releaseImageViewResouce(codeIv);
    }
}
